/**
 * Created by liyun on 2015/10/28.
 */
var knex = require('../utils/knex');
//var Promise = require('bluebird');
var debug = require('debug')('models:activity');
var activity = function(){
    if(typeof this.list !='function'){
        activity.prototype.list = function(page,callback){
            /*knex.select().table('shop_goods').then(function(data){
                callback(data);
            }).catch(function(err){
                callback(err);
            });*/

            countActivity(function(count){
                knex.select('*').from('activity')/*.leftJoin('shop_goods_term',function(){
                    this.on('shop_goods.id','=','shop_goods_term.gid');//条件
                })*/.orderBy(page[0], page[1])//排序
                    .limit(page[3]).offset(page[2])//分页
                    .then(function(data){
                        callback({total:count[0].count,rows:data});
                    }).catch(function(err){
                        callback(err);
                    });
            });

        }

    }

    if(typeof this.add !='function') {
        activity.prototype.add = function (activity, callback) {
            activity.createtime = new Date();
            knex('activity').insert(activity).then(function(data){
                callback({msg:true});
            }).catch(function(err){
                callback({msg:false});
            });

        }
    }

    if(typeof this.edit !='function') {
        activity.prototype.edit = function (activity, callback) {
            delete activity.oldthumb;
            knex('activity')
                .where('id', '=', activity.id)
                .update(activity).then(function(data){
                callback({msg:true});
            }).catch(function(err){
                callback({msg:false});
            });

        }
    }
    if(typeof this.findOne !='function') {
        activity.prototype.findOne = function (id, callback) {
            knex('activity').where('id', '=', id)
                .then(function(data){
                callback(data);
            }).catch(function(err){
                callback(err);
            });

        }
    }

}

function countActivity(callback){
    knex('activity').count('id as count')
        .then(function(data){
        callback(data);
    }).catch(function(err){
        callback(err);
    });
}
module.exports.activity = activity;